<template>
  <div>
    <van-button
      class="follow-btn"
      round
      size="small"
      :loading="isLoading"
      v-if="value"
      @click="followClick"
      >已关注</van-button
    >
    <van-button
      v-else
      class="follow-btn"
      type="info"
      color="#3296fa"
      round
      size="small"
      icon="plus"
      :loading="isLoading"
      @click="followClick"
      >关注</van-button
    >
  </div>
</template>

<script>
import { addUserFollowedApi, deleteUserFollowedApi } from "@/api/article";
export default {
  name: "FollowUser",
  props: {
    //代替isFollowed接收父组件传过来的是否关注的布尔值
    value: {
      type: Boolean,
      required: true,
    },
    authorId: {
      type: [String, Number],
      required: true,
    },
  },
  data() {
    return {
      isLoading: false,
    };
  },
  methods: {
    async followClick() {
      //判断是否登录
      //未登录则提示请登录,并结束进程
      if (!this.$store.getters.token) return this.$toast.fail("请登录");
      //已经登录,则将loading状态设置为true,低俗网下转圈圈,也防止多次点击浪费资源
      this.isLoading = true;
      try {
        if (this.value) {
          //已关注,取消关注
          await deleteUserFollowedApi(this.authorId);
        } else {
          //未关注,则执行关注
          await addUserFollowedApi({
            target: this.authorId,
          });
        }
        //提示成功
        this.$toast.success(this.value ? "取消关注成功" : "关注成功");
        //视图的更新
        this.$emit("input", !this.value);
      } catch (error) {
        this.$toast.fail("操作失败");
        console.log(error);
      }
      this.isLoading = false;
    },
  },
};
</script>

<style lang="less" scoped></style>
